package org.indi.graduatemanagement.controller;


import cn.hutool.core.lang.Assert;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.indi.graduatemanagement.common.lang.Result;
import org.indi.graduatemanagement.entity.Archives;
import org.indi.graduatemanagement.service.ArchivesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zcl
 * @since 2021-04-24
 */
@RestController
@RequiresAuthentication
@RequestMapping("/archives")
public class ArchivesController {

    @Autowired
    ArchivesService archivesService;

    @GetMapping("/{id}")
    @RequiresPermissions("search")
    @RequiresAuthentication //登录后可查询
    public Result getArchivesById(@PathVariable("id") String id) {
        Archives archives = archivesService.getById(id);
        Assert.notNull(archives, "查询错误");
        return Result.successful(archives);
    }

    @PostMapping("/save")
    @RequiresPermissions("add")
    @RequiresAuthentication //登录后可查询
    public Result saveArchives(@Validated @RequestBody Archives archives) {
        if (archivesService.getById(archives.getArchivesStuId()) != null) {
            return Result.fail("信息已存在");
        }
//        Archives archives = new Archives(archivesDto.getArchivesPlace(), archivesDto.getArchivesStuName(),
//                archivesDto.getArchivesStuId(), archivesDto.getArchivesZipcode(), archivesDto.getArchivesId());
        archivesService.save(archives);
        return Result.successful(null);
    }

    @PostMapping("/update")
    @RequiresPermissions("update")
    @RequiresAuthentication //登录后可查询
    public Result updateArchives(@Validated @RequestBody Archives archives) {
        if (archivesService.getById(archives.getArchivesStuId()) == null) {
            return Result.fail("信息不存在");
        }
//        Archives archives = new Archives(archivesDto.getArchivesPlace(), archivesDto.getArchivesStuName(),
//                archivesDto.getArchivesStuId(), archivesDto.getArchivesZipcode(), archivesDto.getArchivesId());
        archivesService.updateById(archives);
        return Result.successful(null);
    }

    @GetMapping("/all")
    @RequiresPermissions("search")
    @RequiresAuthentication //登录后可查询
    public Result getAllArchives() {
        List<Archives> archivesList = archivesService.list();
        return Result.successful(archivesList);
    }

    @DeleteMapping("/{id}")
    @RequiresPermissions("delete")
    @RequiresAuthentication //登录后可查询
    public Result deleteArchivesById(@PathVariable("id") String id) {
        if (archivesService.removeById(id))
            return Result.successful(null);
        else
            return Result.fail("删除失败");
    }

}
